import { WgslReflect } from "wgsl_reflect";
import { NodeShaderLib } from "./shaderlib-ast";
import { parseShaderLib, tryParseShaderLib } from "./shaderlib-parse";
import { ParsingError, ParsingErrorRecorder } from "./shaderlib-err";

interface ShaderCreationResult {
    noError: boolean,
    shader: WebGpuShader,
    errors: Array<ParsingError>
}

export class WebGpuShader {
    private _shaderLibNode: NodeShaderLib

    private constructor(shaderLibNode: NodeShaderLib) {
        this._shaderLibNode = shaderLibNode
    }

    public static createFromShaderLibSource(source: string, filename: string = '<source>'): ShaderCreationResult {
        const result = tryParseShaderLib(source, filename)

        if (!result.noError) {
            return {
                noError: false,
                shader: null,
                errors: result.errors
            }
        }

        const node = result.node

        for (const pass of node.shaderBody.passes) {
            const reflect = new WgslReflect(pass.wgslProgram)
            pass.wgslReflect = reflect
        }

        return {
            noError: true,
            shader: new WebGpuShader(node),
            errors: []
        }
    }
}
